//
//  WebViewController.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2018/9/4.
//  Copyright © 2018年 DUONIU_MAC. All rights reserved.
//

import UIKit
import WebKit
import hpple

class WebViewController: KMViewController {
    
    ///webview
    fileprivate var webView : WKWebView!
    
    ///是否是信用卡专题模块
    var isSpecial = false
    
    //轮播图
    var isCarouselDiagram = false
    
    ///是否显示分享按钮
    var showShare = true
    
    ///链接
    fileprivate var urlStr  = ""
    
    ///进度条
    fileprivate let progressView = UIProgressView()
    
    //分享图片
    fileprivate var shareImage = #imageLiteral(resourceName: "kamenglogo")
    
    fileprivate var shareImageUrl = "" //分享图片链接
    
    fileprivate var shareTitle = "" //分享标题
    
    //分享内容
    fileprivate var shareText = ""
    
    //需要移除的标签
    var removeElements = ["mblock mblocks","app-download","footer"]
    var removeIds = [String]()
    
    init(urlString:String?,title:String? = "",shareImage:String?=nil,shareText:String? = "",shareTitle:String?="") {
        super.init(nibName: nil, bundle: nil)
        
        self.urlStr = urlString ?? ""
        self.title = title
        self.shareText = shareText ?? ""
        self.shareTitle = shareTitle ?? ""
        
        if shareTitle == "" {
            self.shareTitle = self.title ?? ""
        }
        
        if shareImage != nil {
            self.shareImageUrl = shareImage!
        }
    
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
    
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.white
        
        progressView.trackTintColor = UIColor.clear
        progressView.progressTintColor = UIColor.moveColor()
        self.view.addSubview(progressView)
        
        progressView.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(RATIO_H(maxNum: 5))
        }
        
        createWebView()
        
        self.view.bringSubview(toFront: progressView)

        //隐藏返回图标
        self.navigationController?.navigationBar.backIndicatorImage = UIImage()

        //自定义返回图标
        let backButton = UIButton.init(frame: .init(x: 0, y: (StatusBarAddNavBarHeight-StatusBarHeight-30)/2, width: 30, height: 30))
        backButton.setImage(#imageLiteral(resourceName: "back_arrow"), for: .normal)
        backButton.addTarget(self, action: #selector(goBackAction), for: .touchUpInside)
        self.navigationController?.navigationBar.addSubview(backButton)
        
        
    
        addRightBtn()
        
        //信用卡专题
        if isSpecial {
           getSpecialData()
            
        }
        
        //轮播图
        if isCarouselDiagram {
            getSpecialData()
        }
        
        //获取分享内容
        getShareDetails()
        
    }
    
    //MARK: 添加右边按钮
    fileprivate func addRightBtn() {
        
        let barButton = UIBarButtonItem.init(image: #imageLiteral(resourceName: "icon_share"), style: .plain, target: self, action: #selector(webShareAction))
        self.navigationItem.rightBarButtonItem = barButton
    }
    
    //MARK: 网页分享
    @objc fileprivate func webShareAction() {
        
        //如果标题为空则不能分享
        if self.title == nil || self.title == "" {
            return
        }
        
        //分享平台定制
    UMSocialUIManager.setPreDefinePlatforms([NSNumber(integerLiteral: UMSocialPlatformType.sina.rawValue),NSNumber(integerLiteral: UMSocialPlatformType.wechatSession.rawValue),NSNumber(integerLiteral: UMSocialPlatformType.wechatTimeLine.rawValue),NSNumber(integerLiteral: UMSocialPlatformType.QQ.rawValue),NSNumber(integerLiteral: UMSocialPlatformType.qzone.rawValue)])

        
        //调用分享面板
        UMSocialUIManager.showShareMenuViewInWindow { (platformType, userInfo) in
            
            //分享网页
            let messageObject = UMSocialMessageObject()
            let shareObject = UMShareWebpageObject.shareObject(withTitle: self.shareTitle, descr: self.shareText, thumImage: self.shareImageUrl == "" ? self.shareImage : self.shareImageUrl)
            
            shareObject?.webpageUrl = self.urlStr
            messageObject.shareObject = shareObject
            
            UMSocialManager.default().share(to: platformType, messageObject: messageObject, currentViewController: self, completion: { (data, error) in
                
                if error != nil {
                    KMTool.showText(_text: error.debugDescription)
                }else{
                    KMTool.showText(_text: successShare)
                }
                
            })
        }
    }
    
    //MARK: 信用专题页面解析网页
    fileprivate func getSpecialData() {
        
        KMTool.requestGetData(URLString: self.urlStr, parameters: nil,  success: { (data) in
            
            let doc = TFHpple.init(htmlData: data)
            
            if self.isSpecial {
                let imageElements = doc?.search(withXPathQuery: "//div[@class='details clearfloat']/div/div[@class='img_background']/img") as NSArray?
                let imageElement = imageElements?.firstObject
                self.shareImageUrl = kmHttps + (((imageElement as? TFHppleElement)?.object(forKey: "src")) ?? "")
            }
            
            let textElements = doc?.search(withXPathQuery: "//head/meta[@name='description']") as NSArray?
            let textElement = textElements?.firstObject
            self.shareText = (((textElement as? TFHppleElement)?.object(forKey: "content")) ?? "")
            
            
        }) {
            
        }
    }
    

    
    //MARK: 页面回退
    @objc fileprivate func goBackAction() {
        
        if self.webView.canGoBack {
            self.webView.goBack()
        }else{
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    deinit {
        self.webView.removeObserver(self, forKeyPath: "estimatedProgress")
        self.webView.removeObserver(self, forKeyPath: "title")
    }
    
    fileprivate func createWebView() {
        
        self.webView = WKWebView.init(frame: .zero)
        //路径编码
        let string = self.urlStr.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
        if let url = URL.init(string: string ?? "") {
            let request = URLRequest.init(url: url)
            webView.load(request)
        }
        webView.navigationDelegate = self
        webView.uiDelegate = self
        self.view.addSubview(webView)
        
        self.webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
        self.webView.addObserver(self, forKeyPath: "title", options: .new, context: nil)
        
        webView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.zero)
        }
        
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        if "estimatedProgress" == keyPath {
            self.progressView.setProgress(Float(self.webView.estimatedProgress), animated: true)
            if self.progressView.progress == 0 {
                self.progressView.isHidden = false
            }else if self.progressView.progress == 1 {
                DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                    if self.progressView.progress == 1 {
                        self.progressView.progress = 0
                        self.progressView.isHidden = true
                    }
                }
            }
        }else if "title" == keyPath {
            
            if self.title == nil || self.title == "" {
                self.title = self.webView.title
                self.shareTitle = self.webView.title ?? self.shareTitle
            }
        }
        
        let removeElement = KMTool.removeHtmlElement(classNames: self.removeElements)
        webView.evaluateJavaScript(removeElement, completionHandler: nil)
        let removeId = KMTool.removeHtmlElementForId(idNames: self.removeIds)
        webView.evaluateJavaScript(removeId, completionHandler: nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

extension WebViewController : WKNavigationDelegate,WKUIDelegate {
    
    //MARK: 页面加载失败
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        
        KMTool.showText(_text: global_requestFailed)
    }

    

    //MARK: 页面加载成功
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {

        let removeElement = KMTool.removeHtmlElement(classNames: self.removeElements)
        webView.evaluateJavaScript(removeElement, completionHandler: nil)
        let removeId = KMTool.removeHtmlElementForId(idNames: self.removeIds)
        webView.evaluateJavaScript(removeId, completionHandler: nil)
        KMTool.showText(_text: global_loadSuccess)
        
        //加载文章
        if self.urlStr.contains("m.kameng98.com/mposts") || self.urlStr.contains("m.kameng98.com/marticle") {
            
            getShareDetails()
        }
        

    }

    //MARK: 拦截网页点击事件
    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
        
        let urlString = navigationResponse.response.url?.absoluteString

        if urlString! == self.urlStr {
            decisionHandler(.allow)
            return
        }

        if !(urlString!.contains("kameng98.com")) && !(urlString!.contains("https://static.bshare.cn/cm.html")) {

            KMTool.generateRecords(idString: self.urlStr)
            
            let webDetailsVC = WebDetailsViewController.init(urlString: urlString)
            self.navigationController?.pushViewController(webDetailsVC, animated: true)

            decisionHandler(.cancel)
            return
        }

        //卡片页面
        if (urlString?.contains("m.kameng98.com/mobile/details/i"))! {

            let webVC = WebViewController.init(urlString: urlString, title: nil)
            self.navigationController?.pushViewController(webVC, animated: true)
            decisionHandler(.cancel)
            return
        }
        
        //文章页面
        if (urlString?.contains("m.kameng98.com/mposts"))! || (urlString?.contains("m.kameng98.com/marticle"))! {
            
            if (urlString?.contains("m.kameng98.com/mposts"))! {
                removeElements = ["mblock mblocks","crumbs mblock","footer1","bsPromo bsPromo1"]
                removeIds = ["xiong_div"]
            }else{
                removeElements = ["mbloc mblocks","crumbs mblock","footer1","bsPromo bsPromo1"]
                removeIds = ["xiong_div"]
            }
            
            self.urlStr = urlString!
            
            if let url = URL.init(string: self.urlStr) {
                let request = URLRequest.init(url: url)
                webView.load(request)
            }
        }

        //资讯文章新卡速递
        if (urlString?.contains("details"))! {
            
            let id = urlString?.replacingOccurrences(of: "https://www.kameng98.com/details/", with: "")
            let string = webUrl + "/mobile/details/i" + id!
            
            let webVC = WebViewController.init(urlString: string)
            webVC.isSpecial = true
            self.navigationController?.pushViewController(webVC, animated: true)
            decisionHandler(.cancel)
            return
        }
        

        decisionHandler(.allow)

    }
    
    //MARK: 加载新网页
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        
        if navigationAction.targetFrame != nil {
            if !(navigationAction.targetFrame?.isMainFrame)! {
                webView.evaluateJavaScript("var a = document.getElementsByTagName('a');for(var i=0;i<a.length;i++){a[i].setAttribute('target','');}", completionHandler: nil)
            }
        }
        
        //贷款文章新口子
        if (navigationAction.request.url?.absoluteString.contains("daikuandetail"))! {
            
            let id = navigationAction.request.url?.absoluteString.replacingOccurrences(of: "https://www.kameng98.com/daikuandetail/", with: "")
            
            let loanDetailsWebVC = LoanDetailsWebViewController.init(urlStr: id ?? "", title: webView.title!)
            loanDetailsWebVC.hidesBottomBarWhenPushed = true
            loanDetailsWebVC.removeElements = ["top-bar","footer"]
            self.navigationController?.pushViewController(loanDetailsWebVC, animated: true)
        }
        
        decisionHandler(.allow)
    }
    
    
}

extension WebViewController {
    
    //MARK: 获取文章分享详情
    fileprivate func getShareDetails() {
        
        if (self.urlStr.contains("m.kameng98.com/mposts")) || (self.urlStr.contains("m.kameng98.com/marticle")) {
            
            KMTool.requestGetData(URLString: self.urlStr, parameters: nil,  success: { (data) in
                
                let doc = TFHpple.init(htmlData: data)
                
                let titleElements = doc?.search(withXPathQuery: "//div[@id='article_content']/h2") as NSArray?
                let titleElement = titleElements?.firstObject
                self.shareTitle = (titleElement as? TFHppleElement)?.text() ?? ""
                
                let textElements = doc?.search(withXPathQuery: "//head/meta[@name='description']") as NSArray?
                let textElement = textElements?.firstObject
                self.shareText = (((textElement as? TFHppleElement)?.object(forKey: "content")) ?? "")
                
                

                //获取分享图片
                let string = NSString.init(data: data, encoding: String.Encoding.utf8.rawValue)
                let startRange = string?.range(of: "<div id=\"article_content\">")
                let endRange = string?.range(of: "<div class=\"zan\">")
                
                let range = NSMakeRange((startRange?.location)! + (startRange?.length)!, (endRange?.location)! - (startRange?.location)! - (startRange?.length)!)
                let result = string?.substring(with: range)
                let resultData = result?.data(using: String.Encoding.utf8)
                
                let doc2 = TFHpple.init(htmlData: resultData)
                
                let imageElements = doc2?.search(withXPathQuery: "//img") as NSArray?
                let imageElement = imageElements?.firstObject
                
                if let imageUrl = (imageElement as? TFHppleElement)?.object(forKey: "src") {
                    
                    self.shareImageUrl = kmHttps + imageUrl
                }
                
                
                
            }) {
                
            }
        }
    }
}
